<template>
  <view class="filter-page">
    <!-- 顶部导航 -->
    <uni-nav-bar 
      title="筛选订单" 
      left-icon="left" 
      :border="false"
      background-color="#fff"
      @clickLeft="handleBack"
    >
      <template #right>
        <text class="reset-btn" @click="handleReset">重置</text>
      </template>
    </uni-nav-bar>

    <scroll-view scroll-y class="filter-content">
      <!-- 快速筛选标签 -->
      <view class="filter-section">
        <view class="section-title">快速筛选</view>
        <view class="quick-tags">
          <view 
            v-for="tag in quickTags" 
            :key="tag.key"
            class="quick-tag"
            :class="{ active: selectedQuickTag === tag.key }"
            @click="selectQuickTag(tag.key)"
          >
            {{ tag.label }}
          </view>
        </view>
      </view>

      <!-- 门店筛选 -->
      <view class="filter-section">
        <view class="section-title">门店</view>
        <uni-data-select
          v-model="filterParams.store_id"
          :localdata="storeOptions"
          placeholder="请选择门店"
          @change="onStoreChange"
        ></uni-data-select>
      </view>

      <!-- 场地筛选 -->
      <view class="filter-section">
        <view class="section-title">场地</view>
        <uni-data-select
          v-model="filterParams.venue_id"
          :localdata="venueOptions"
          placeholder="请选择场地"
          :disabled="!filterParams.store_id"
        ></uni-data-select>
      </view>

      <!-- 订单状态 -->
      <view class="filter-section">
        <view class="section-title">订单状态</view>
        <uni-data-checkbox
          v-model="filterParams.status"
          :localdata="statusOptions"
          multiple
        ></uni-data-checkbox>
      </view>

      <!-- 支付状态 -->
      <view class="filter-section">
        <view class="section-title">支付状态</view>
        <uni-data-checkbox
          v-model="filterParams.payment_status"
          :localdata="paymentStatusOptions"
          multiple
        ></uni-data-checkbox>
      </view>

      <!-- 时间范围 -->
      <view class="filter-section">
        <view class="section-title">时间范围</view>
        <view class="date-range">
          <uni-datetime-picker
            v-model="filterParams.start_date"
            type="date"
            placeholder="开始日期"
            @change="onStartDateChange"
          ></uni-datetime-picker>
          <text class="date-separator">至</text>
          <uni-datetime-picker
            v-model="filterParams.end_date"
            type="date"
            placeholder="结束日期"
            @change="onEndDateChange"
          ></uni-datetime-picker>
        </view>
      </view>

      <!-- 金额范围 -->
      <view class="filter-section">
        <view class="section-title">金额范围</view>
        <view class="amount-range">
          <uni-easyinput
            v-model="filterParams.min_amount"
            type="number"
            placeholder="最小金额"
            @input="onAmountChange"
          ></uni-easyinput>
          <text class="amount-separator">-</text>
          <uni-easyinput
            v-model="filterParams.max_amount"
            type="number"
            placeholder="最大金额"
            @input="onAmountChange"
          ></uni-easyinput>
        </view>
      </view>
    </scroll-view>

    <!-- 底部操作按钮 -->
    <view class="filter-footer safe-area-inset-bottom">
      <button class="filter-btn secondary" @click="handleReset">重置</button>
      <button class="filter-btn primary" @click="handleConfirm">确认筛选</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { fetchStores } from '@/api/store';
import { fetchVenuesByStore } from '@/api/store';
import type { Store, Venue } from '@/types/store';
import { OrderStatus, PaymentStatus } from '@/types/order';

// 筛选参数
const filterParams = reactive({
  store_id: null as number | null,
  venue_id: null as number | null,
  status: [] as OrderStatus[],
  payment_status: [] as PaymentStatus[],
  start_date: '',
  end_date: '',
  min_amount: '',
  max_amount: '',
});

// 原始筛选参数（用于重置）
const originalParams = ref({});

// 快速筛选标签
const quickTags = [
  { key: 'today', label: '今日订单' },
  { key: 'week', label: '本周订单' },
  { key: 'month', label: '本月订单' },
  { key: 'pending', label: '待处理' },
  { key: 'high_value', label: '高价值订单' },
];

const selectedQuickTag = ref('');

// 门店和场地数据
const stores = ref<Store[]>([]);
const venues = ref<Venue[]>([]);

// 选项数据
const storeOptions = computed(() => 
  stores.value.map(store => ({ value: store.id, text: store.name }))
);

const venueOptions = computed(() => 
  venues.value.map(venue => ({ value: venue.id, text: venue.name }))
);

const statusOptions = [
  { value: OrderStatus.Pending, text: '待处理' },
  { value: OrderStatus.Confirmed, text: '已确认' },
  { value: OrderStatus.Completed, text: '已完成' },
  { value: OrderStatus.Cancelled, text: '已取消' },
  { value: OrderStatus.Rescheduled, text: '已改签' },
];

const paymentStatusOptions = [
  { value: PaymentStatus.Unpaid, text: '未支付' },
  { value: PaymentStatus.Paid, text: '已支付' },
  { value: PaymentStatus.Refunded, text: '已退款' },
];

// 获取门店列表
const getStores = async () => {
  try {
    const res = await fetchStores({ page: 1, pageSize: 100 });
    stores.value = res.list;
  } catch (error) {
    console.error('获取门店列表失败:', error);
  }
};

// 门店变更时获取场地列表
const onStoreChange = async (storeId: number) => {
  filterParams.venue_id = null; // 重置场地选择
  if (storeId) {
    try {
      const res = await fetchVenuesByStore(storeId);
      venues.value = res.list;
    } catch (error) {
      console.error('获取场地列表失败:', error);
      venues.value = [];
    }
  } else {
    venues.value = [];
  }
};

// 快速筛选标签选择
const selectQuickTag = (tagKey: string) => {
  selectedQuickTag.value = tagKey;
  const today = new Date();
  
  switch (tagKey) {
    case 'today':
      filterParams.start_date = formatDate(today);
      filterParams.end_date = formatDate(today);
      break;
    case 'week':
      const weekStart = new Date(today);
      weekStart.setDate(today.getDate() - today.getDay());
      filterParams.start_date = formatDate(weekStart);
      filterParams.end_date = formatDate(today);
      break;
    case 'month':
      const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
      filterParams.start_date = formatDate(monthStart);
      filterParams.end_date = formatDate(today);
      break;
    case 'pending':
      filterParams.status = [OrderStatus.Pending];
      break;
    case 'high_value':
      filterParams.min_amount = '1000';
      break;
  }
};

// 日期格式化
const formatDate = (date: Date) => {
  return date.toISOString().split('T')[0];
};

// 日期变更处理
const onStartDateChange = (date: string) => {
  filterParams.start_date = date;
};

const onEndDateChange = (date: string) => {
  filterParams.end_date = date;
};

// 金额变更处理
const onAmountChange = () => {
  // 可以添加金额验证逻辑
};

// 重置筛选
const handleReset = () => {
  Object.assign(filterParams, {
    store_id: null,
    venue_id: null,
    status: [],
    payment_status: [],
    start_date: '',
    end_date: '',
    min_amount: '',
    max_amount: '',
  });
  selectedQuickTag.value = '';
  venues.value = [];
};

// 确认筛选
const handleConfirm = () => {
  // 构建筛选参数
  const params: any = {};
  
  if (filterParams.store_id) params.store_id = filterParams.store_id;
  if (filterParams.venue_id) params.venue_id = filterParams.venue_id;
  if (filterParams.status.length > 0) params.status = filterParams.status;
  if (filterParams.payment_status.length > 0) params.payment_status = filterParams.payment_status;
  if (filterParams.start_date) params.start_date = filterParams.start_date;
  if (filterParams.end_date) params.end_date = filterParams.end_date;
  if (filterParams.min_amount) params.min_amount = parseFloat(filterParams.min_amount) * 100; // 转换为分
  if (filterParams.max_amount) params.max_amount = parseFloat(filterParams.max_amount) * 100; // 转换为分

  // 返回上一页并传递筛选参数
  const pages = getCurrentPages();
  const prevPage = pages[pages.length - 2];
  if (prevPage) {
    prevPage.$vm.applyFilter(params);
  }
  
  uni.navigateBack();
};

// 返回上一页
const handleBack = () => {
  uni.navigateBack();
};

onLoad((options: any) => {
  // 接收传入的筛选参数
  if (options.params) {
    try {
      const params = JSON.parse(decodeURIComponent(options.params));
      Object.assign(filterParams, params);
      originalParams.value = { ...params };
    } catch (error) {
      console.error('解析筛选参数失败:', error);
    }
  }
});

onMounted(() => {
  getStores();
});
</script>

<style lang="scss" scoped>
.filter-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--background-color);
}

.reset-btn {
  color: var(--primary-color);
  font-size: 14px;
}

.filter-content {
  flex: 1;
  height: 0;
  padding-bottom: 80px;
}

.filter-section {
  background-color: #fff;
  margin-bottom: 10px;
  padding: 15px;

  .section-title {
    font-size: 16px;
    font-weight: bold;
    color: var(--text-color);
    margin-bottom: 10px;
  }
}

.quick-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;

  .quick-tag {
    padding: 6px 12px;
    background-color: #f5f5f5;
    border-radius: 15px;
    font-size: 12px;
    color: var(--text-color-secondary);
    
    &.active {
      background-color: var(--primary-color);
      color: #fff;
    }
  }
}

.date-range {
  display: flex;
  align-items: center;
  gap: 10px;

  .date-separator {
    color: var(--text-color-secondary);
    font-size: 14px;
  }
}

.amount-range {
  display: flex;
  align-items: center;
  gap: 10px;

  .amount-separator {
    color: var(--text-color-secondary);
    font-size: 14px;
  }
}

.filter-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 15px;
  display: flex;
  gap: 15px;
  border-top: 1px solid #eee;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);

  .filter-btn {
    flex: 1;
    height: 44px;
    border-radius: var(--border-radius);
    font-size: 16px;
    margin: 0;

    &.primary {
      background-color: var(--primary-color);
      color: #fff;
    }

    &.secondary {
      background-color: #f5f5f5;
      color: var(--text-color);
      border: 1px solid #d9d9d9;
    }
  }
}
</style>